﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;

namespace ComprUtils
{
  public class UnZip : BackgroundWorker, ComprUtils.IUnpack
  {
    FastZip _fz;
    FastZipEvents _fze;
    string _zipFilename;
    int _totalFilesInZip;
    
    public UnZip()
    {
      _fze = new FastZipEvents();
      _fz = new FastZip(_fze);
    }
    public string PackFilename
    {
      get { return _zipFilename; }
      set { _zipFilename = value; }
    }
    string _targetDir;
    public string TargetDir
    {
      get { return _targetDir; }
      set { _targetDir = value; }
    }

    public List<string> GetListFromPack()
    {
      ZipFile zf = null;
      List<string> list = new List<string>();
      zf = new ZipFile(_zipFilename);
      IEnumerator enu = zf.GetEnumerator();
      while (enu.MoveNext())
      {
        ZipEntry zen = enu.Current as ZipEntry;
        if (zen.IsDirectory)
          continue;//ignore directories
        list.Add(zen.Name);
      }
      return list;
    }

    protected override void OnDoWork(DoWorkEventArgs e)
    {
      ExtractPack();
      base.OnDoWork(e);
    }

    public void ExtractPack()
    {
      _totalFilesInZip = GetListFromPack().Count;
      _iCount = 0;
      _fze.ProcessFile = new ICSharpCode.SharpZipLib.Core.ProcessFileDelegate(ProcessFile);
      _fz.ExtractZip(_zipFilename, _targetDir, "");
      this.ReportProgress(100);
    }

    int _iCount = 0; // callback function
    void ProcessFile(object sender, ScanEventArgs e) 
    {
      int perc = Convert.ToInt32(Math.Min(100,_iCount*100/_totalFilesInZip));
      _iCount++;
      this.ReportProgress(perc,e.Name);
    }
  }
}
